package com.sqly.doc.menu.grjbxx;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.inuker.bluetooth.library.search.SearchResult;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.R;
import com.sqly.doc.adapter.MyBLEListAdapter;
import com.sqly.doc.base.MyBaseActivity;
import com.sqly.doc.ble.xyjnew.SocketPressureActivity;
import com.sqly.doc.interFace.IBleScanListener;
import com.sqly.doc.interFace.IBleStateListener;
import com.sqly.doc.interFace.IPermissionsListener;
import com.sqly.doc.pojo.BleMeasureRecord;
import com.sqly.doc.pojo.JuMin;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.user.choose_user;
import com.sqly.doc.util.HttpUrl;
import com.sqly.doc.util.MyToastUtil;
import com.sqly.doc.util.NetWorkUtils;
import com.sqly.doc.util.SharedPreferencesUtils;
import com.sqly.doc.util.SweetAlertDialogUtil;
import com.sqly.doc.util.UserClient;
import com.sqly.doc.util.ZBleManager;
import com.sqly.doc.util.ZPermissionUtil;
import com.sqly.doc.view.StringUtils;

import cz.msebera.android.httpclient.Header;

public class measure_xy_new_add extends MyBaseActivity  implements View.OnClickListener, IPermissionsListener, IBleStateListener {
    TextView kfxyz, kfxyz2, kfxyz3, title, uname, xm, jmid, jmsfzh,sbzt;
    BleMeasureRecord obj;
    Context con = measure_xy_new_add.this;
    JuMin j;
    private String url = "";
    boolean isadd = false;//是否是新添加
    LinearLayout back;

    SearchResult searchResultDevice = null;
    //设备相关
    private RecyclerView mRv;
    private TextView mTvStart;
    private LinearLayout mLLStart;
    private ProgressBar mProgress;
    private MyBLEListAdapter mAdapter;
    private boolean isStart = false;
    private ZBleManager mBleManager;

    @Override
    protected void initUI() {
        setContentView(R.layout.measure_xy_new_add);
        if (getIntent().getStringExtra("type").equals("edit")) {
            obj = (BleMeasureRecord) getIntent().getExtras().getSerializable("b");
            url = HttpUrl.EditGxyfsjl;
            initEditText();
            xm.setClickable(false);
        } else {
            obj=new BleMeasureRecord();
            url = HttpUrl.AddGxyfsjl;
            initEditText();
        }
        initAboutBleView();

        back = (LinearLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        initAboutBleView();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {

        } else if (requestCode == 1) {
            j = (JuMin) data.getExtras().getSerializable("j");
            getObject();
        }else if(requestCode == 19){
            String deviceVal = (String) data.getExtras().getString("deviceVal");
            String deviceVal2 = (String) data.getExtras().getString("deviceVal2");
            String deviceVal3 = (String) data.getExtras().getString("deviceVal3");
            kfxyz.setText(deviceVal);
            kfxyz2.setText(deviceVal2);
            kfxyz3.setText(deviceVal3);
        }
    }


    private void initAboutBleView(){
        initList();
        initListener();
        if (!ZPermissionUtil.getInstance().isPermissions(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
            ZPermissionUtil.getInstance().requestPermissions(this, this, Manifest.permission.ACCESS_COARSE_LOCATION);
        } else {
            isStart = true;
            initScan();
        }
    }

    private void initEditText() {
        xm = (TextView) findViewById(R.id.xm);
        if (obj != null && !StringUtils.isEmpty(obj.getJmname())) {
            xm.setText(obj.getJmname());
        } else {
            xm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivityForResult(new Intent(con, choose_user.class).putExtra("cname", "measure_xy_add.class"), 1);
                }
            });
        }
        sbzt = (TextView) findViewById(R.id.sbzt);
        jmid = (TextView) findViewById(R.id.jmid);
        jmsfzh = (TextView) findViewById(R.id.jmsfzh);
        //空腹血压值
        kfxyz = (TextView) findViewById(R.id.kfxyz);
        kfxyz2 = (TextView) findViewById(R.id.kfxyz2);
        kfxyz3 = (TextView) findViewById(R.id.kfxyz3);
        View.OnClickListener onClickListener= new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String xyjval = (String) SharedPreferencesUtils.getParam(con, "xyjval", "");
                if(null == xyjval || "".equals(xyjval)) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请先绑定蓝牙血压计设备");
                }else if (obj != null && StringUtils.isEmpty(obj.getJmname())) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击用户输入框选择用户");
                } else if(null != searchResultDevice) {
                    Intent intent = new Intent(measure_xy_new_add.this, SocketPressureActivity.class);
                    intent.putExtra("device", searchResultDevice);
                    startActivityForResult(intent, 19);
                }else{
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "未发现设备，请启动血压计电源");
                }
            }
        };
        kfxyz.setOnClickListener(onClickListener);
        kfxyz2.setOnClickListener(onClickListener);
        kfxyz3.setOnClickListener(onClickListener);
        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("居民血压测量");
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (obj == null)
                    obj = new BleMeasureRecord();
                obj.setVal1(kfxyz.getText().toString());
                obj.setVal2(kfxyz2.getText().toString());
                obj.setVal3(kfxyz3.getText().toString());

                if (null == xm.getText().toString() || xm.getText().toString().equals("")) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击用户输入框选择用户");
                } else if (null == kfxyz.getText().toString() || kfxyz.getText().toString().equals("")) {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", "请点击血压值输入框进行血压测量");
                } else if (NetWorkUtils.isNetworkConnected(con)) {
                    RequestParams ps = new RequestParams();
                    ps.add("entity.category", "2");
                    ps.add("entity.jmid", obj.getJmid());
                    ps.add("entity.jmname", obj.getJmname());
                    ps.add("entity.jmsfzh", obj.getJmsfzh());
                    ps.add("entity.val1", obj.getVal1());
                    ps.add("entity.val2", obj.getVal2());
                    ps.add("entity.val3", obj.getVal3());
                    ps.add("entity.blename", obj.getBlename());
                    ps.add("entity.blemac", obj.getBlemac());
                    ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                    ps.add("type", "2");
                    if (isadd) {
                        url = HttpUrl.AddBleMRecord;
                    } else {
                        ps.add("entity.id", obj.getRid());
                        url = HttpUrl.SaveBleMRecord;
                    }
                    UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                            String content = new String(response);
                            RetMsg ret = JSON.parseObject(content, RetMsg.class);
                            if (ret.getCode().equals("200")) {
                                MyToastUtil.ShowToast(con, "成功");
                            }else{
                                MyToastUtil.ShowToast(con, ret.getInfo());
                            }
                            finish();
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                            MyToastUtil.ShowToast(con, "失败");
                        }
                    });
                }
            }
        });

        //设备
        mRv = findViewById(R.id.rv_list);
        mTvStart = findViewById(R.id.tv_start);
        mLLStart = findViewById(R.id.ll_start);
        mProgress = findViewById(R.id.progress);
    }

    public void initListener() {
//        mRv.addOnItemTouchListener(new OnItemClickListener() {
//            @Override
//            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
//                Intent intent = new Intent(measure_xy_new_add.this, SocketPressureActivity.class);
//                SearchResult device = mAdapter.getData().get(position);
//                intent.putExtra("device", device);
//                startActivity(intent);
//            }
//        });
//        mLLStart.setOnClickListener(this);
        sbzt.setOnClickListener(this);
    }

    private void initList() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRv.setLayoutManager(linearLayoutManager);
        mRv.addItemDecoration(new DividerItemDecoration(this, linearLayoutManager.getOrientation()));
        mAdapter = new MyBLEListAdapter(null);
        mRv.setAdapter(mAdapter);
    }


    private void initScan() {
        mBleManager = ZBleManager.getInstance();
        mBleManager.initBle(this);
        if (mBleManager.isSupportBle()) {
            if (!mBleManager.isBlueOpen()) {
                mBleManager.openBluetooth(this);
            } else {
                bleScan();
            }
        } else {
            Toast.makeText(this, R.string.device_not_support, Toast.LENGTH_LONG).show();
        }
    }

    private void bleScan() {
        mBleManager.scan(new IBleScanListener() {
            @Override
            public void onScanStarted() {
                mAdapter.setNewData(null);
                mTvStart.setText(R.string.stop);
                mProgress.setVisibility(View.VISIBLE);
                Log.e("zdw", "onScanStarted");
            }

            @Override
            public void onScanCanceled() {

            }

            @Override
            public void onScanStop() {
//                mTvStart.setText(R.string.start);
                mProgress.setVisibility(View.GONE);
                Log.e("zdw", "onScanFinished");
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                if (device == null) return;
                if (!device.getName().contains("Bioland-BPM")) return;
                if (!mAdapter.getData().contains(device)) {
                    mAdapter.addData(device);
                    Log.e("zdw", "onScanning" + device.getAddress());
                    String xyjval = (String) SharedPreferencesUtils.getParam(measure_xy_new_add.this, "xyjval", "");
                    if (device.getAddress().equals(xyjval)) {
                        searchResultDevice = device;
                        ZBleManager.getInstance().cancelScan();
                        sbzt.setText("已发现设备");
                    }
                }
            }

        });
    }

    @Override
    public void onBleOpen() {
        bleScan();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_start:
                if (!isStart) {
                    isStart = true;
                    initScan();
                } else {
                    isStart = false;
                    mProgress.setVisibility(View.GONE);
                    mTvStart.setText(R.string.start);
                }
                break;
            case R.id.sbzt:
                if (!isStart) {
                    isStart = true;
                    initScan();
                } else {
                    isStart = false;
                    mProgress.setVisibility(View.GONE);
                    mTvStart.setText(R.string.start);
                }
                break;
        }
    }

    @Override
    public void onPermissionsSuccess() {
        isStart = true;
        initScan();
    }

    @Override
    public void onPermissionsFail() {
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        ZBleManager.getInstance().cancelScan();
    }

    public void getObject() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("CARDNUM", j.getCARDNUM());
        UserClient.get(HttpUrl.GetXxfhGrjbxx, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] response) {
                String content = new String(response);
                Log.i("ycf2", content);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    if (StringUtils.isEmpty(ret.getOtherParams())) {//other是空的
                        JSONObject j = JSON.parseObject(ret.getRd());
                        obj = new BleMeasureRecord();
                        obj.setJmid(j.getString("JKDAH"));
                        obj.setJmname(j.getString("XINGMING"));
                        obj.setJmsfzh(j.getString("SFZH"));
                        xm.setText(j.getString("XINGMING"));
                        jmid.setText(j.getString("JKDAH"));
                        jmsfzh.setText(j.getString("SFZH"));
                        isadd = true;
                    } else {
                        obj = JSON.parseObject(ret.getRd(), BleMeasureRecord.class);
                    }
                } else {
                    SweetAlertDialogUtil.WarningDialog(con, "提示", ret.getInfo());
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {

                isadd = true;
                obj = new BleMeasureRecord();
            }
        });
    }
}
